# -*- coding: utf-8 -*-
import json
import requests

from config.config import ACLOUD_URL, POST_LOGIN_DATA, \
    ACLOUD_LOGIN, default_data, version_url, wirte_js_route

requests.packages.urllib3.disable_warnings()
base_url = ACLOUD_URL
session = requests.Session()
try:
    session.post(ACLOUD_LOGIN, data=POST_LOGIN_DATA, verify=False)
    version = session.get(ACLOUD_URL + version_url)
    version_json = version.json()
    session.headers['X-HCI-REQUIRED'] = version_json['data']['api_version']
except:
    session.headers['X-HCI-REQUIRED'] = "5.8.7.R1"


def create_json(request):
    """
    :param path: 为获取到的请求地址，转发请求真实地址获取对应数据
    :return: 将真实数据写入json文件并写入路由
    """
    method = request.method.lower()
    form_data = request.form.to_dict()
    files = request.files.to_dict()
    data_json = request.json
    path = request.path
    query_string = request.query_string
    request_url = base_url + path + '?' + query_string
    # 将所有请求类型都转发
    request_data = getattr(session, method)(request_url,
                                            data=form_data,
                                            json=data_json,
                                            files=files,
                                            verify=False)
    status_code = request_data.status_code
    try:
        data = request_data.json()
        if method == 'put':
            status_code = 200
    except:
        data = default_data
        status_code = 200

    data = json.dumps(data)
    wirte_js_route(data, path, status_code)
    return data, status_code
